/**
 * 
 */
package com.gmail.blackdog1987.carcare.activity;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.gmail.blackdog1987.carcare.BaseActivity;
import com.gmail.blackdog1987.carcare.R;

public class MapGuidActivity extends BaseActivity implements OnClickListener, OnGetPoiSearchResultListener, OnGetRoutePlanResultListener {
	// 定位相关

	LocationClient mLocClient;
	BitmapDescriptor mCurrentMarker;
	MapView mMapView;
	BaiduMap mBaiduMap;
	Button myLocButton;
	Button destnationButton;
	MyDrivingRouteOverlay overlay;

	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;

	private boolean isFirstLoc = true;// 是否首次定位

	private InfoWindow mInfoWindow;
	private RoutePlanSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用

	BDLocation myLocation;
	double lat;
	double lng;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mapguid);
		lat = getIntent().getDoubleExtra("lat", 0);
		lng = getIntent().getDoubleExtra("lng", 0);
		if (lat == 0 || lng == 0) {
			Toast.makeText(MapGuidActivity.this, "对不起，尚未录入该地点信息", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		initViews();
	}

	@Override
	public void initViews() {

		myLocButton = (Button) findViewById(R.id.button1);
		destnationButton = (Button) findViewById(R.id.button2);

		// 地图初始化

		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();

		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(14.0f);
		mBaiduMap.setMapStatus(msu);

		// 开启定位图层

		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化

		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		final LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps

		option.setCoorType("bd09ll"); // 设置坐标类型

		// option.setScanSpan(1000);

		mLocClient.setLocOption(option);
		mLocClient.start();

		destnationButton.setText("我");
		destnationButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (overlay != null) {
					overlay.removeFromMap();
				}
//				mBaiduMap.hideInfoWindow();
				if(myLocation!=null){
					MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
					mBaiduMap.animateMapStatus(u);
				}else{
					Toast.makeText(MapGuidActivity.this, "正在为您定位", Toast.LENGTH_LONG).show();
				}
			}
		});
		myLocButton.setText("导航");
		myLocButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mLocClient.requestLocation();
				mLocClient.start();
			}
		});

		mSearch = RoutePlanSearch.newInstance();
		mSearch.setOnGetRoutePlanResultListener(this);
	}

	private static LatLng mLatLng;

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			myLocation = location;
			if (location == null || mMapView == null) {
				return;
			}

			MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius()).direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);

			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}

			PlanNode stNode = PlanNode.withLocation(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
			PlanNode enNode = PlanNode.withLocation(new LatLng(lat, lng));

			mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位

		mLocClient.stop();
		// 关闭定位图层

		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	@Override
	public void onClick(View arg0) {

	}

	@Override
	public void onGetPoiDetailResult(final PoiDetailResult result) {

		if (result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		} else {
		}
	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		System.err.println("searching finish......");
		if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			Toast.makeText(this, "未找到结果", Toast.LENGTH_LONG).show();
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			mBaiduMap.clear();
			mBaiduMap.setOnMarkerClickListener(overlay);
			overlay.addToMap();
			// overlay.zoomToSpan();
			return;
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

			// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表

			String strInfo = "在";
			for (CityInfo cityInfo : result.getSuggestCityList()) {
				strInfo += cityInfo.city;
				strInfo += ",";
			}
			strInfo += "找到结果";
			Toast.makeText(this, strInfo, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {

		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
			// 起终点或途经点地址有岐义，通过以下接口获取建议查询信息

			// result.getSuggestAddrInfo()

			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			// int nodeIndex = -1;
			// mBtnPre.setVisibility(View.VISIBLE);

			// mBtnNext.setVisibility(View.VISIBLE);

			// RouteLine route = result.getRouteLines().get(0);
			overlay = new MyDrivingRouteOverlay(mBaiduMap);
			mBaiduMap.setOnMarkerClickListener(overlay);
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult arg0) {

	}

	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult arg0) {

	}

	// 定制RouteOverly

	private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

		public MyDrivingRouteOverlay(BaiduMap baiduMap) {
			super(baiduMap);
		}

		@Override
		public BitmapDescriptor getStartMarker() {
			return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
		}

		@Override
		public BitmapDescriptor getTerminalMarker() {
			return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
		}
	}
}